#import "HWHttpTool.h"
#import "MBProgressHUD.h"
#define kMallRequestTimeoutInterval 20


static AFHTTPSessionManager *manager;
//static AFURLSessionManager *urlsession;//这个还没用到
//@interface AFHTTPSessionSharedManager : AFHTTPSessionManager
//@end
@implementation AFHTTPSessionSharedManager

+ (AFHTTPSessionManager *)sharedHTTPSession{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 1.创建请求管理者
        manager = [AFHTTPSessionManager manager];
        //超过20秒请求超时
        manager.requestSerializer.timeoutInterval = kMallRequestTimeoutInterval;
//        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/plain", nil];
       manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/javascript",@"text/html",@"text/plain",nil];
    });
//    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    if ([manager.requestSerializer.HTTPRequestHeaders.allKeys containsObject:@"X-AUTH-TOKEN"]) {
        [manager.requestSerializer setValue:nil forHTTPHeaderField:@"X-AUTH-TOKEN"];

    }

    return manager;
}
+ (void)cancelURLSessionTask:(NSURLSessionTask *)task
{
    if (task) {
        [task cancel];
    }
}
@end
@implementation HWHttpTool
+(NSURLSessionDataTask *)requestWithMethod:(NSString *)method url:(NSString *)url params:(NSDictionary *)params headers:(NSDictionary *)headers success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    AFHTTPSessionManager *session = [AFHTTPSessionSharedManager sharedHTTPSession];
        session.requestSerializer = [AFHTTPRequestSerializer serializer];
        session.responseSerializer = [AFJSONResponseSerializer serializer];
    if (headers) {
        [headers enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            [session.requestSerializer  setValue:obj  forHTTPHeaderField:key];
        }];
    }
    NSURLSessionDataTask *task;
    if ([method isEqualToString:@"GET"]) {
        task = [session GET:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (success) {
                success(responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            NSHTTPURLResponse *response = error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey];
//            
//            NSInteger statusCode = response.statusCode;

            if (task.state == NSURLSessionTaskStateCompleted && error.code == -999 ) {
                DLog(@"失败:取消");
                return;
            }
            DLog(@"失败:%@",task.currentRequest.URL);
            if (failure) {
                failure(error);
            }
        }];
    } else {
        [session POST:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            DLog(@"%@",task.currentRequest.URL);
            
            if (success) {
                success(responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            if (task.state == NSURLSessionTaskStateCompleted && error.code == -999 ) {
                DLog(@"失败:取消");
                return;
            }
            DLog(@"失败:%@",task.currentRequest.URL);
            if (failure) {
                failure(error);
            }
        }];
    }
    
    return task;
}
+ (NSURLSessionDataTask *)get:(NSString *)url params:(NSDictionary *)params success:(void (^)(id json))success failure:(void (^)(NSError *error))failure{
    
    AFHTTPSessionManager *session = [AFHTTPSessionSharedManager sharedHTTPSession];
    NSURLSessionDataTask *task = [session GET:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DLog(@"%@",task.currentRequest.URL);
        if (task.state == NSURLSessionTaskStateCompleted && error.code == -999 ) {
            DLog(@"失败:取消");
            return;
        }
        DLog(@"失败:%@",task.currentRequest.URL);
        if (failure) {
            failure(error);
        }
    }];
    return task;
}

+ (NSURLSessionDataTask *)post:(NSString *)url params:(NSDictionary *)params success:(void (^)(id json))success failure:(void (^)(NSError *error))failure{
    
    // 1.创建请求管理者
//    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
//    session.requestSerializer.timeoutInterval = kMallRequestTimeoutInterval;
//    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/plain", nil];

    AFHTTPSessionManager *session = [AFHTTPSessionSharedManager sharedHTTPSession];
    // 2.发送请求
    NSURLSessionDataTask *task = [session POST:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DLog(@"%@",task.currentRequest.URL);

        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        DLog(@"%@",task.currentRequest.URL);
        if (task.state == NSURLSessionTaskStateCompleted && error.code == -999 ) {
            DLog(@"失败:取消");
            return;
        }
        DLog(@"失败:%@",task.currentRequest.URL);
        if (failure) {
            failure(error);
        }
    }];
    return task;
}
//带图层指示框的get请求
+ (NSURLSessionDataTask *)getWithHUD:(UIView *)view WithUrl:(NSString *)url params:(NSDictionary *)params success:(void (^)(id json))success failure:(void (^)(NSError *error))failure{
    
    // 1.创建请求管理者
//    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
//    session.requestSerializer.timeoutInterval = kMallRequestTimeoutInterval;
//    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/plain", nil];
    AFHTTPSessionManager *session = [AFHTTPSessionSharedManager sharedHTTPSession];
    [MBProgressHUD showHUDAddedTo:view animated:YES];
    
    // 2.发送请求
  NSURLSessionDataTask * task = [session GET:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:view animated:YES];
        DLog(@"%@",task.currentRequest.URL);
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DLog(@"%@",task.currentRequest.URL);
        [MBProgressHUD hideHUDForView:view animated:YES];
        if (task.state == NSURLSessionTaskStateCompleted && error.code == -999 ) {
            DLog(@"失败:取消");
            return;
        }
        DLog(@"失败:%@",task.currentRequest.URL);
        if (failure) {
            failure(error);
        }
    }];
    return task;
}

//带图层指示框的get请求回参为data类型
+ (void)getAddDataWithHUD:(UIView *)view WithUrl:(NSString *)url params:(NSDictionary *)params success:(void (^)(id json))success failure:(void (^)(NSError *error))failure{
    
    // 1.创建请求管理者
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = kMallRequestTimeoutInterval;
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/plain", nil];
    session.requestSerializer = [AFHTTPRequestSerializer serializer];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    if (view != nil) {
        [MBProgressHUD showHUDAddedTo:view animated:YES];
    }
    // 2.发送请求
    [session GET:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *shabi =  [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSError *err;
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject
                                                           options:NSJSONReadingMutableContainers
                                                             error:&err];
        [MBProgressHUD hideHUDForView:view animated:YES];
        if (success) {
            if (jsonDic!=nil) {
                success(jsonDic);
            }else{
                success(shabi);
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:view animated:YES];
        if (failure) {
            failure(error);
        }
        
    }];
    
}

//带图层指示框的post请求
+ (NSURLSessionDataTask *)postWithHUD:(UIView *)view WithUrl:(NSString *)url params:(NSDictionary *)params success:(void (^)(id json))success failure:(void (^)(NSError *error))failure{
    
    // 1.创建请求管理者
    AFHTTPSessionManager *session = [AFHTTPSessionSharedManager sharedHTTPSession];
//    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
//    session.requestSerializer.timeoutInterval = kMallRequestTimeoutInterval;
//    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/plain", nil];
    [MBProgressHUD showHUDAddedTo:view animated:YES];
    // 2.发送请求
   NSURLSessionDataTask *task = [session POST:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DLog(@"成功:%@",task.currentRequest.URL);
        [MBProgressHUD hideHUDForView:view animated:YES];
        if (success) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DLog(@"失败:%@  原因:%@",task.currentRequest.URL,[error localizedDescription]);

        [MBProgressHUD hideHUDForView:view animated:YES];
        if (task.state == NSURLSessionTaskStateCompleted && error.code == -999 ) {
            DLog(@"失败:取消");
            return;
        }
        if (failure) {
            failure(error);
        }
    }];
    return task;
}
//带图层指示框的post请求回参为data类型
+ (void)postAddDataWithHUD:(UIView *)view WithUrl:(NSString *)url params:(NSDictionary *)params success:(void (^)(id json))success failure:(void (^)(NSError *error))failure{
    
    // 1.创建请求管理者
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = kMallRequestTimeoutInterval;
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/plain", nil];
    session.requestSerializer = [AFHTTPRequestSerializer serializer];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    if (view != nil) {
        [MBProgressHUD showHUDAddedTo:view animated:YES];
    }
    // 2.发送请求
    [session POST:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *shabi =  [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSError *err;

        NSDictionary * jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject
                                                                 options:NSJSONReadingMutableContainers
                                                                   error:&err];
        [MBProgressHUD hideHUDForView:view animated:YES];
        if (success) {
            if (jsonDic != nil) {
                success(jsonDic);
            }else{
                success(shabi);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:view animated:YES];
        if (failure) {
            failure(error);
        }
    }];
    
    
}


+ (void)postJson:(NSString *)url params:(NSDictionary *)params success:(void (^)(id json))success failure:(void (^)(NSError *error))failure{
    
    // 1.创建请求管理者
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer = [AFJSONRequestSerializer serializer];
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/plain",@"text/json", nil];
    // 2.发送请求
    [session POST:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
        
    }];
    
}


//文件上传(图片)
+ (void)post:(NSString *)url params:(NSDictionary *)params fileDatas:(NSArray *)fileDatas name:(NSString *)name fileNames:(NSArray *)fileNames mimeTypes:(NSArray *)mineTypes success:(void (^)(id json))success failure:(void (^)(NSError *error))failure{
    
    // 1.创建一个管理者
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = kMallRequestTimeoutInterval;
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"image/png", @"text/plain",nil];//,@"text/plain"
    [session.requestSerializer setValue:[[UserInfoManager shareUser]token] forHTTPHeaderField:@"X-AUTH-TOKEN"];//设置请求头
    // 2.发送请求
    
    [session POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        // 在发送请求之前会自动调用这个block
        // 需要在这个block中添加文件参数到formData中
        if (fileDatas.count == fileNames.count && fileNames.count == mineTypes.count) {
            for (int i = 0; i < fileDatas.count; i++) {
                [formData appendPartWithFileData:fileDatas[i] name:name fileName:fileNames[i] mimeType:mineTypes[i]];
            }
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
        
    }];
   

}
+ (void)post:(NSString *)url params:(NSDictionary *)params fileData:(NSData *)fileData name:(NSString *)name fileName:(NSString *)fileName mimeType:(NSString *)mineType success:(void (^)(id json))success failure:(void (^)(NSError *error))failure
{
    // 1.创建一个管理者
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    manger.requestSerializer.timeoutInterval = kMallRequestTimeoutInterval;
//    manger.requestSerializer = [AFHTTPRequestSerializer serializer];
    manger.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"image/png",@"text/plain", nil];//,
    
    // 2.发送请求
    
    [manger POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        // 在发送请求之前会自动调用这个block
        // 需要在这个block中添加文件参数到formData中
                [formData appendPartWithFileData:fileData name:name fileName:fileName mimeType:mineType];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
        
    }];
    
}
//带有指示图层的图片上传
+ (NSURLSessionDataTask *)postWithHUD:(UIView *)view WithUrl:(NSString *)url params:(NSDictionary *)params fileData:(NSData *)fileData name:(NSString *)name fileName:(NSString *)fileName mimeType:(NSString *)mineType success:(void (^)(id json))success failure:(void (^)(NSError *error))failure{
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = kMallRequestTimeoutInterval;
//    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    session.responseSerializer = [AFJSONResponseSerializer serializer];
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"image/png",@"text/plain", nil];
    [MBProgressHUD showHUDAddedTo:view animated:YES];
    NSURLSessionDataTask * task = [session POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:fileData name:name fileName:fileName mimeType:mineType];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DLog(@"成功:%@",task.currentRequest.URL);
        [MBProgressHUD hideHUDForView:view animated:YES];
        if (success) {
            success(responseObject);
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:view animated:YES];
        if (failure) {

            failure(error);
        }
        
    }];
    return task;
}

//文件下载
+ (void)downloadTaskWithURL:(NSString *)urlstr  completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler{
    
    // 获得网络管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = kMallRequestTimeoutInterval;
    // 创建请求对象
    NSURL *url = [NSURL URLWithString:urlstr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 声明一个进度对象
    [[manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        // 告诉服务器下载的文本保存的位置在哪里
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        completionHandler(response,filePath,error);
    }] resume];
    
}

+ (NSURLSessionDataTask *)postWithHUDInSuperView:(UIView *)view UrlString:(NSString *)url params:(NSDictionary *)params errorText:(NSString *)errText noData:(NSString *)text success:(void (^)(id json))success failure:(void (^)(NSError *error))failure reload:(void (^)(id sender)) reload{
    
    // 1.创建请求管理者
    AFHTTPSessionManager *session = [AFHTTPSessionSharedManager sharedHTTPSession];
//    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
//    session.requestSerializer.timeoutInterval = kMallRequestTimeoutInterval;
    [MBProgressHUD showHUDAddedTo:view animated:YES];
//    [KHUI_Helper hiddenNetworkViewInSuperView:view];
//    KHUIView_Network *errView = [KHUI_Helper networkViewInSuperView:view];
//    typeof(KHUIView_Network*) adErrView = errView;
//    errView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
//    if (errText) {
//        errView.errorText = errText;
//    }
//    if (text) {
//        errView.text = text;
//    }
//    errView.block_click = ^(id sender){
//        [adErrView removeFromSuperview];
//        reload(sender);
//    };
    
    // 2.发送请求
    //get
//        [session GET:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
//    
//        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            DLog(@"成功:%@",task.currentRequest.URL);
//            if (success) {
//                success(responseObject);
//                if (responseObject == nil) {
//                    errView.hasData = NO;
//                }else{
//                    errView.hasData = YES;
//                }
//            }
//            [MBProgressHUD hideHUDForView:view animated:YES];
//    
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            DLog(@"失败:%@",task.currentRequest.URL);
//            [MBProgressHUD hideHUDForView:view animated:YES];
//            DLog(@"失败:%@",task.currentRequest.URL);
//            
//            if (failure) {
//                errView.error = error;
//                failure(error);
//            }
//
//    
//        }];
  NSURLSessionDataTask *task = [session POST:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DLog(@"成功:%@",task.currentRequest.URL);
        [MBProgressHUD hideHUDForView:view animated:YES];

        if (success) {
            success(responseObject);
            if (responseObject == nil) {
//                errView.hasData = NO;
            }else{
//                errView.hasData = YES;
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [MBProgressHUD hideHUDForView:view animated:YES];
        DLog(@"失败:%@",task.currentRequest.URL);
        
        if (failure) {
//            errView.error = error;
            failure(error);
        }
    }];
    return task;
    
}


@end
